var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var queryurl = config.BASEPATH+'sort/allot/pageAllotDetailReport';
var _height = $(parent).height()-180,_width = $(parent).width()-32;
var api = frameElement.api, W = api.opener;

var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择配货门店',
			content : 'url:'+config.BASEPATH+'base/shop/list_dialog_bymodule',
			data : {multiselect:true,module:'allot'},
			width : 480,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var sp_code = [];
				var sp_name = [];
				for(var i=0;i<selected.length;i++){
					sp_code.push(selected[i].sp_code);
					sp_name.push(selected[i].sp_name);
				}
				$("#at_shop_code").val(sp_code.join(","));
				$("#shop_name").val(sp_name.join(","));
			},
			cancel:true
		});
	},
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择经办人',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#at_manager").val(selected.em_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#at_manager").val(selected.em_name);
				}
			},
			cancel:true
		});
	},
	doQueryDepot : function(code,name){
		commonDia = $.dialog({
			title : '选择仓库',
			content : 'url:'+config.BASEPATH+'base/depot/to_list_dialog_bymodule',
			data : {multiselect:false,module:'allot'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#"+code).val(selected.dp_code);
				$("#"+name).val(selected.dp_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#"+code).val(selected.dp_code);
					$("#"+name).val(selected.dp_name);
				}
			},
			cancel:true
		});
	},
	doQueryBrand : function(){
		commonDia = $.dialog({
			title : '选择品牌',
			content : 'url:'+config.BASEPATH+'base/brand/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].bd_code);
					names.push(selected[i].bd_name);
				}
				$("#bd_code").val(codes.join(","));
				$("#bd_name").val(names.join(","));
			},
			close:function(){
			},
			cancel:true
		});
	},
	doQueryType : function(){
		commonDia = $.dialog({
			title : '选择类别',
			content : 'url:'+config.BASEPATH+'base/type/to_tree_dialog',
			data : {multiselect:true},
			width : 300,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].tp_code);
					names.push(selected[i].tp_name);
				}
				$("#tp_code").val(codes.join(","));
				$("#tp_name").val(names.join(","));
			},
			close:function(){
			},
			cancel:true
		});
	},
	doQueryProduct : function(){
		commonDia = $.dialog({
			title : '选择商品',
			content : 'url:'+config.BASEPATH+'base/product/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#pd_code").val(selected.pd_code);
				$("#pd_name").val(selected.pd_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#pd_code").val(selected.pd_code);
					$("#pd_name").val(selected.pd_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	formatApplyMoney:function(val, opt, row){
		if(row.atl_unitprice == undefined){
			return PriceLimit.formatByDistribute(val);
		}
		return PriceLimit.formatByDistribute(row.atl_unitprice * row.atl_applyamount);
	},
	formatSendMoney:function(val, opt, row){
		if(row.atl_unitprice == undefined){
			return PriceLimit.formatByDistribute(val);
		}
		return PriceLimit.formatByDistribute(row.atl_unitprice * row.atl_sendamount);
	},
	formatSendCostMoney:function(val, opt, row){
		if(row.atl_costprice == undefined){
			return PriceLimit.formatByCost(val);
		}
		return PriceLimit.formatByCost(row.atl_costprice * row.atl_sendamount);
	},
	formatType:function(val, opt, row){
		if(val == 0){
			return '配货单';
		}else if(val == 1){
			return '退货单';
		}
		return val;
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();
	},
	initDom:function(){
		this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		dateRedioClick("theDate");
		this.$_at_type = $("#td_at_type").cssRadio({ callback: function($_obj){
			$("#at_type").val($_obj.find("input").val());
		}});
		this.$_state = $("#td_state").cssRadio({ callback: function($_obj){
			$("#at_ar_state").val($_obj.find("input").val());
		}});
		this.initParams();
		this.initSeason();
		this.initYear();
	},
	initParams:function(){
		var params = api.data;
		$("#begindate").val($.trim(params.begindate));
		$("#enddate").val($.trim(params.enddate));
		$("#shop_name").val($.trim(params.shop_name));
		$("#at_shop_code").val($.trim(params.at_shop_code));
		$("#outdepot_name").val($.trim(params.outdepot_name));
		$("#at_outdp_code").val($.trim(params.at_outdp_code));
		$("#indepot_name").val($.trim(params.indepot_name));
		$("#at_indp_code").val($.trim(params.at_indp_code));
		$("#at_manager").val($.trim(params.at_manager));
		$("#bd_name").val($.trim(params.bd_name));
		$("#bd_code").val($.trim(params.bd_code));
		$("#tp_name").val($.trim(params.tp_name));
		$("#tp_code").val($.trim(params.tp_code));
		$("#pd_season").val($.trim(params.pd_season));
		$("#pd_year").val($.trim(params.pd_year));
		$("#pd_code").val($.trim(params.pd_code));
		$("#pd_name").val($.trim(params.pd_name));
		if($.trim(params.at_type) != ''){
			THISPAGE.$_at_type.setValue(parseInt(params.at_type)+1);
		}
		if($.trim(params.at_ar_state) != ''){
			THISPAGE.$_state.setValue(parseInt(params.at_ar_state)-2);
		}
	},
	initSeason:function(){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"base/dict/list?dtl_upcode=KEY_SEASON",
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.data != "" && data.data.length > 0){
					var seasons = data.data;
					seasons.unshift({dtl_code:"",dtl_name:"全部"});
					$('#span_pd_season').combo({
						value : 'dtl_code',
						text : 'dtl_name',
						width : 207,
						listHeight : 300,
						listId : '',
						defaultSelected : 0,
						editable : false,
						callback : {
							onChange : function(data) {
								if(data.dtl_code != ""){
									$("#pd_season").val(data.dtl_name);
								}else{
									$("#pd_season").val("");
								}
							}
						}
					}).getCombo().loadData(seasons,["dtl_name",$("#pd_season").val(),0]);
				}
			}
		 });
	},
	initYear:function(){
		var currentYear = new Date().getFullYear();
		var data = [
		    {Code:"",Name:"全部"},
			{Code:""+parseInt(currentYear+1)+"",Name:""+parseInt(currentYear+1)+""},
			{Code:""+parseInt(currentYear)+"",Name:""+parseInt(currentYear)+""},
			{Code:""+parseInt(currentYear-1)+"",Name:""+parseInt(currentYear-1)+""},
			{Code:""+parseInt(currentYear-2)+"",Name:""+parseInt(currentYear-2)+""},
			{Code:""+parseInt(currentYear-3)+"",Name:""+parseInt(currentYear-3)+""},
			{Code:""+parseInt(currentYear-4)+"",Name:""+parseInt(currentYear-4)+""},
			{Code:""+parseInt(currentYear-5)+"",Name:""+parseInt(currentYear-5)+""}
		];
		$('#span_pd_year').combo({
			value: 'Code',
			text: 'Name',
			width :206,
			height:80,
			listId:'',
			defaultSelected: 0,
			editable: false,
			callback:{
				onChange: function(data){
					$("#pd_year").val(data.Code);
				}
			}
		}).getCombo().loadData(data,["Code",$("#pd_year").val(),0]);
	},
	initGrid:function(){
		var colModel = [
		    {label:'操作',name:'operate', width: 40, fixed:true, formatter: Public.operImgFmatter,align:'center'},
	    	{label:'日期',name: 'at_date',index:'at_date',width:100},
	    	{label:'单据编号',name: 'atl_number',index:'atl_number',width:135},
	    	{label:'单据类型',name: 'atl_type',index:'atl_type',width:100,formatter: handle.formatType,align:'center'},
	    	{label:'店铺名称',name: 'shop_name',index:'shop_name',width:100},
	    	{label:'发货仓库',name: 'outdp_name',index:'outdp_name',width:100},
	    	{label:'收货仓库',name: 'indp_name',index:'indp_name',width:100},
	    	{label:'商品货号',name: 'pd_no',index:'pd_no',width:100},
	    	{label:'',name: 'atl_pd_code',index:'atl_pd_code',width:100,hidden:true},
	    	{label:'商品名称',name: 'pd_name',index:'pd_name',width:100},
	    	{label:'颜色',name: 'cr_name', index: 'cr_name', width: 60},
	    	{label:'尺码',name: 'sz_name', index: 'sz_name', width: 60},
	    	{label:'杯型',name: 'br_name', index: 'br_name', width: 60,align:'center'},
	    	{label:'单位',name: 'pd_unit', index: 'pd_unit', width: 60,align:'center'},
	    	{label:'零售价',name: 'atl_unitprice', index: 'atl_unitprice', width: 80,align:'right',formatter: PriceLimit.formatByDistribute},
	    	{label:'成本价',name: 'atl_costprice', index: 'atl_costprice', width: 80,align:'right',formatter: PriceLimit.formatByCost},
	    	{label:'申请数量',name: 'atl_applyamount', index: 'atl_applyamount', width: 70,align:'right'},
	    	{label:'实发数量',name: 'atl_sendamount', index: 'atl_sendamount', width: 70,align:'right'},
	    	{label:'申请金额',name: 'atl_applymoney', index: 'atl_applymoney', width: 80,align:'right',formatter: handle.formatApplyMoney},
	    	{label:'实发金额',name: 'atl_sendmoney', index: 'atl_sendmoney', width: 80,align:'right',formatter: handle.formatSendMoney},
	    	{label:'实发成本',name: 'atl_sendcost', index: 'atl_sendcost', width: 80,align:'right',formatter: handle.formatSendCostMoney},
	    	{label:'品牌',name: 'bd_name', index: 'pd_bd_code', width: 80},
	    	{label:'类别',name: 'tp_name', index: 'pd_tp_code', width: 80},
	    	{label:'季节',name: 'pd_season', index: 'pd_season', width: 80,align:'center'},
	    	{label:'年份',name: 'pd_year', index: 'pd_year', width: 80,align:'center'}
	    ];
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'local',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:false,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			userDataOnFooter: true,
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
                userdata: 'data.data',
				repeatitems : false,
				id: 'atl_id'  //图标ID
			},
			loadComplete: function(data){
		    	$('#grid').footerData('set',{at_date:"合计"});
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	buildParams : function(){
		var params = '';
		params += 'at_type='+$("#at_type").val();
		params += '&at_ar_state='+$("#at_ar_state").val();
		params += '&begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&at_shop_code='+$("#at_shop_code").val();
		params += '&at_outdp_code='+$("#at_outdp_code").val();
		params += '&at_indp_code='+$("#at_indp_code").val();
		params += '&bd_code='+$("#bd_code").val();
		params += '&tp_code='+$("#tp_code").val();
		params += '&pd_season='+$("#pd_season").val();
		params += '&pd_year='+$("#pd_year").val();
		params += '&at_manager='+Public.encodeURI($("#at_manager").val());
		params += '&pd_code='+$("#pd_code").val();
		return params;
	},
	reset:function(){
		$("#pd_code").val("");
		$("#pd_name").val("");
		$("#at_manager").val("");
		$("#shop_name").val("");
		$("#at_shop_code").val("");
		$("#outdepot_name").val("");
		$("#at_outdp_code").val("");
		$("#indepot_name").val("");
		$("#at_indp_code").val("");
		$("#bd_name").val("");
		$("#bd_code").val("");
		$("#tp_name").val("");
		$("#tp_code").val("");
		THISPAGE.$_date.setValue(0);
		THISPAGE.$_at_type.setValue(0);
		THISPAGE.$_state.setValue(0);
		$("#span_pd_season").getCombo().selectByValue("");
		$("#span_pd_year").getCombo().selectByValue("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
		$('#grid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#grid").jqGrid("getRowData", id).atl_pd_code);
        });
	}
}
THISPAGE.init();